import React from 'react';
import { Modal, Form, Input, message } from 'antd';

import { FormInstance } from 'antd/lib/form';
import { BlackListInfo } from '../../../../schema/BlackList';
import { createBlackList } from '../../../../servers/servers';
import { verifyTelephone } from 'utils/tools';

/**
 * 黑名单props
 */
interface IProps {
  callback?: any; //获取暴露方法
}

/**
 * 黑名单state
 */
interface IState {
  // 当前操作弹出弹窗的可见性
  visible: boolean;
}

/**
 * 黑名单管理操作：新增
 */
export class BlackListPop extends React.Component<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  // 当前的黑名单信息
  private BlackListInfo?: BlackListInfo;

  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      ...props,
      visible: false,
    };
  }

  /**
   * 展开弹窗并设置类型
   */
  public open(): void {
    this.setState({
      visible: true,
    });
  }

  /**
   * 关闭弹窗
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**
   * 设置表单值
   */
  public setValue(val: BlackListInfo) {
    setTimeout(() => {
      this.BlackListInfo = val;
      this.formRef.current?.setFieldsValue(val);
    }, 0);
  }

  /**
   * 提交 新增 的数据
   */
  private submitData(): void {
    const form = this.formRef.current;
    form?.validateFields().then(res => {
      const { phoneNumber } = form.getFieldsValue();
      createBlackList({ phoneNumber })
        .then(res => {
          if (res.code === 0) {
            message.success('创建成功');
            this.close();
            this.props.callback();
          } else {
            message.error(`${res.tips}(错误码: ${res.code})`);
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  render() {
    const { visible } = this.state;
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };

    return (
      <>
        <Modal
          title="新建号码"
          width={560}
          visible={visible}
          onOk={() => {
            this.submitData();
          }}
          onCancel={() => {
            this.close();
          }}
        >
          <Form {...layout} layout="horizontal" ref={this.formRef}>
            <Form.Item
              label="黑名单号码"
              name="phoneNumber"
              validateFirst
              rules={verifyTelephone}
              getValueFromEvent={event => {
                return event.target.value.replace(/[^0-9]+/g, '');
              }}
            >
              <Input placeholder="请输入黑名单号码" minLength={7} maxLength={11} />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
}
